//
//  MineViewController.m
//  TMSDriver
//
//  Created by mac on 2019/6/13.
//  Copyright © 2019年 zhuchongjin. All rights reserved.
//

#import "MineViewController.h"
#import "LogInVC.h"
#import "MineFooterView.h"
#import "PersonInforVC.h"
#import "MyAccountInforVC.h"
#import "MyBankCartVC.h"
#import "MyAccountInforVCNew.h"
// 下部11个分类
#import "AppeptGroupVC.h"
#import "ShipperAuthVC.h"
#import "PolicyOrderListVC.h"
#import "LegalAdviceVC.h"
#import "DataStatisticsVC.h"
#import "CommonInforVC.h"
#import "MyEvaluationVC.h"
#import "ComplainsRecordsVC.h"
#import "AdviceFeedbackVC.h"
#import "CommonProblemVC.h"
#import "AboutOurVC.h"
#import "ContractListVC.h"
#import "InvoiceClaimNewVC.h"
#import "CompanyMembersVC.h" // 公司成员
#import "ShipperContractListVC.h"
#import "CashDepositVC.h"
#import "MineCell.h"
#import "AccountBalanceModel.h"
#import "StrongReminderView.h"
#import "CompanyMembersModel.h"
#import "XLImageViewer.h"
#import "ZTXInforQYViewController.h"

@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource>{
    FlexFrameView *header;
}
@property (strong, nonatomic) CJTableView *tableView;
@property (nonatomic,strong)NSMutableArray *arrImgsList;
@property (nonatomic,strong)NSMutableArray *arrTitlesList;

@property (strong, nonatomic) MineFooterView *footerView;
@property (nonatomic,copy) NSDictionary *dicUserInfo;
@property (nonatomic, strong) UIImageView *bgImagView;
@property (nonatomic, strong) UIImageView *erWeimaImagView;
//    ----
@property (nonatomic,strong) CJImageView *imgVheader;
@property (nonatomic,strong) CJLabel *labName;
@property (nonatomic,strong) CJLabel *labPhone;
//保证金
@property (nonatomic,strong) FlexTouchView *touchViewCashDeposit; //
@property (nonatomic,strong) CJLabel *labMoney; //余额
@property (strong, nonatomic) CJLabel *labCashDepMoney; //保证金年
@property (strong, nonatomic) CJLabel *labBankCartNum; // 银行卡

@property (strong, nonatomic) UIImage *erWeiMaImag;
@property (strong, nonatomic) UIView *bgView;
@property (strong, nonatomic) UIImageView *erwImagView;
@property (strong, nonatomic) UILabel *nameLabel;
@property (nonatomic, strong) UITapGestureRecognizer *changeVoidceSet;
@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTitleName:@"我的"];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
//    self.image.hidden = YES;
    [self getArrTitleAndContent];
    [self createTableViewHeader];
    [self setWhiterColorAppNavigationBarStyle];
    
    WS(ws);
    [CJNetWork getBrachcCodeSuccess:^(id  _Nullable responseObject) {
        [ws makeHeaderView];
        ws.footerView.labPhone.text = CJStringWithFormat(@"全国24小时服务热线 \n %@",[CJControl getThreeUnaryValueStr:responseObject[@"telephone"]]);
    }];

}

- (void)getUSerInfo{
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/collectionAccountCheck/balance",CJBaseUrl);
    NSDictionary *dicPar = [[NSDictionary alloc]init];
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
         // platformBalance  平台
        // mybankBalance 网商
        NSError * error ;
        AccountBalanceModel *model = [[AccountBalanceModel alloc]initWithDictionary:responseObject error:&error];
//        ws.labMoney.text = CJStringWithFormat(@"%0.2f",model.platformBalance + model.mybankBalance);
        double allMoney = model.platformBalance + model.mybankBalance;
        if(model.staffType == 3){
            ws.labMoney.text = @(model.financeVirtualAmount).cj_money_description;
        }else{
            ws.labMoney.text = @(allMoney).cj_money_description;
        }
       
        [ws.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
    
    [CJNetWork getPartyUserCenterInfoSuccess:^(id responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        DLog(@"+++++ %@",dic);
        
        ws.dicUserInfo = dic;
        ws.labPhone.text = [CJControl getThreeUnaryValueStr:dic[@"phone"]];
        ws.labName.text = [CJControl getThreeUnaryValueStr:dic[@"name"]];
        [ws.imgVheader sd_setImageWithURL:[NSURL URLWithString:dic[@"headImg"]] placeholderImage:UIImageNamed(@"zcj_default_person_icon")];
        
        ws.labBankCartNum.text = [CJControl getThreeUnaryValueStr:dic[@"bankCardNum"]];
//        ws.headerView.labMoney.text = CJStringWithFormat(@"%@",dic[@"balance"]);
        
//        float bancle = [CJStringWithFormat(@"%@",dic[@"balance"]) floatValue];
//         ws.labMoney.text = CJStringWithFormat(@"%0.2lf",bancle );
//        isEnsure (integer, optional): 是否需要发货保证金，0否/1是
//        ensureFee (number, optional): 保证金基准额度
//        ensureFeeAmount (number, optional):  保证金账户余额
        NSString *strIsEnsure = CJStringWithFormat(@"%@",dic[@"isEnsure"]);
//        strIsEnsure = @"1";
        if ([strIsEnsure isEqualToString:@"0"]) {
            ws.touchViewCashDeposit.hidden = YES;

        }else if([strIsEnsure isEqualToString:@"1"]){
            
            ws.touchViewCashDeposit.hidden = NO;
            ws.labCashDepMoney.text = @([[CJControl getThreeUnaryValueStr:dic[@"ensureFeeAmount"]] floatValue]).cj_money_description;
        }

        if ([CJControl getIdCardDateHasDue] && [CJControl getStrongReminderShow]) {
            [[[StrongReminderView shared]initWithView] show];
        }else{
            [[[StrongReminderView shared]initWithView] hidden];
        }
        [ws getArrTitleAndContent];
        [ws.tableView.mj_header endRefreshing];

    }];
    
}
- (void)getUserCenterNetworking{
    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/party/merchant",CJBaseUrl);
    NSDictionary *dicPra = nil;
    
    [[HDNetworking sharedHDNetworking] GET:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {

        NSLog(@"%@",responseObject);
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
// 下拉刷新
- (void)headerRereshing{
    [self makeHeaderView];
}

- (void)makeHeaderView{
    
    if ([CJControl isLogin]) {
        [self getUSerInfo];
        [self getUserCenterNetworking];
        [self huizhiErWeiMa];
        self.erWeimaImagView.hidden = NO;
    }else{
        self.labName.text = @"登录 / 注册";
        self.labPhone.text = @"";
        [self.tableView.mj_header endRefreshing];
        self.erWeimaImagView.hidden = YES;
    }
}

- (void)createTableViewHeader{
    //    WS(ws);
    CGRect rcFrame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 0);
//    [CJControl getUIWithNew] ? @"MineHeaderViewNew":@"MineHeaderView"
    if (!header) {
        header = [[FlexFrameView alloc] initWithFlex:@"MineHeaderView" Frame:rcFrame Owner:self];
    }
    header.flexibleHeight = YES;
    self.bgImagView.userInteractionEnabled = YES;
    self.imgVheader.userInteractionEnabled = YES;
    self.erWeimaImagView.userInteractionEnabled = YES;
    [header layoutIfNeeded];
    [self.view addSubview:header];
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
}
//绘制二维码
- (void)huizhiErWeiMa{
    //1. 实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2. 恢复滤镜的默认属性
    [filter setDefaults];
    // 3. 将字符串转换成NSData
    NSString *urlStr = CJStringWithFormat(@"%@/bindDriver?type=OwnersQRCode&code=%@&page=subpages/driver/bind",CJBaseUrl,[CJControl getPartyCode]);
    NSData *data = [urlStr dataUsingEncoding:NSUTF8StringEncoding];
    // 4. 通过KVO设置滤镜inputMessage数据
    [filter setValue:data forKey:@"inputMessage"];
    // 5. 获得滤镜输出的图像
    CIImage *outputImage = [filter outputImage];
    // 6. 将CIImage转换成UIImage，并显示于imageView上 (此时获取到的二维码比较模糊,所以需要用下面的createNonInterpolatedUIImageFormCIImage方法重绘二维码)
    UIImage *img = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:SCREEN_WIDTH - 60];//重绘二维码,使其显示清晰
    self.erWeimaImagView.image = img;
    self.erWeiMaImag = img;
}
#pragma mark ----------点击事件
/// 头部点击事件
- (void)erWeimaAction{//点击二维码
    [[UIApplication sharedApplication].keyWindow addSubview:self.bgView];
}
- (void)btnTouchViewMineHeaderAction{

    DLog(@"头视图点击事件");

    if ([CJControl isLogin]) {
        PersonInforVC *vc = [PersonInforVC new];
        [self pushVc:vc];
    }else{
        [self showLoginWindow];
    }
}
/// 账户信息
- (void)btnTouchAccountInfoAction{
    
    if ([CJControl isLogin]) {

        if ([CJControl getUIWithNew]) {
            MyAccountInforVCNew *vc = [MyAccountInforVCNew new];
            vc.strMoney = self.labMoney.text;
            [self pushVc:vc];
        }else{
            MyAccountInforVC *vc = [MyAccountInforVC new];
            vc.strMoney = self.labMoney.text;
            [self pushVc:vc];
        }
    }else{

        [self showLoginWindowALert];
    }
}
/// 保证金
- (void)btnTouchCashDepositAction{
    
    if ([CJControl isLogin]) {
        CashDepositVC *vc = [CashDepositVC new];
        [self pushVc:vc];
    }else{

        [self showLoginWindowALert];
    }

}
/// 银行卡
- (void)btnTouchBankNumsAction{
    
    if ([CJControl isLogin]) {
        MyBankCartVC *vc = [MyBankCartVC new];
        [self pushVc:vc];
    }else{
        [self showLoginWindowALert];
    }
}

/// 认证
- (void)btnTouchViewShipperAuthAction{
    ShipperAuthVC *vc = [ShipperAuthVC new];
    [self pushVc:vc];
}
//合同
- (void)btnTouchViewContractListAction{
    ContractListVC *vc = [ContractListVC new];
    [self pushVc:vc];
}

/// 我的评价
- (void)btnTouchViewMyEvaluationAction{
    MyEvaluationVC *vc = [MyEvaluationVC new];
    [self pushVc:vc];
}
// 投诉
- (void)btnTouchViewComplainsRecordsAction{
    ComplainsRecordsVC *vc = [ComplainsRecordsVC new];
    [self pushVc:vc];
}

#pragma mark----tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrTitlesList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"MineCell";
    MineCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[MineCell alloc] initWithFlex:@"MineCell" reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    BOOL show;
    if ([CJControl getShowAccountBalanceVisafree] && [self.arrTitlesList[indexPath.row] isEqualToString:@"免验授权"]) {
        cell.detailTextLabel.text = [CJControl getAccountBalanceVisafreeAuthStatus];
        show = YES;
    }else{
        show = NO;
    }
    
    [cell setCellInfoimgVHeader:self.arrImgsList[indexPath.row] cellTitle:self.arrTitlesList[indexPath.row] index:indexPath.row isOnShowAouth:show];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *strTitle = self.arrTitlesList[indexPath.row];

    UIViewController *vc;
    if ([strTitle isEqualToString:@"认证信息"]) {
        vc = [ShipperAuthVC new];
    }else if ([strTitle isEqualToString:@"公司成员"]) {
        [self didSelectCompanyMembersAction];
        return;
        
    }else if ([strTitle isEqualToString:@"保单列表"]) {
        vc = [PolicyOrderListVC new];
    }else if ([strTitle isEqualToString:@"电子合同"]) {
        vc = [ContractListVC new];
    }else if ([strTitle isEqualToString:@"货主合同"]) {
        vc = [ShipperContractListVC new];
    }else if ([strTitle isEqualToString:@"发票索取"]) {
        vc = [InvoiceClaimNewVC new];
    }else if ([strTitle isEqualToString:@"承运分组"]) {
        vc = [AppeptGroupVC new];
    }else if ([strTitle isEqualToString:@"法律咨询"]) {
        vc = [LegalAdviceVC new];
    }else if ([strTitle isEqualToString:@"数据统计"]) {
        vc = [DataStatisticsVC new];
    }else if ([strTitle isEqualToString:@"常用信息"]) {
        vc = [CommonInforVC new];
    }else if ([strTitle isEqualToString:@"我的评价"]) {
        vc = [MyEvaluationVC new];
    }else if ([strTitle isEqualToString:@"投诉记录"]) {
        vc = [ComplainsRecordsVC new];
    }else if ([strTitle isEqualToString:@"投诉意见反馈"]) {
        vc = [AdviceFeedbackVC new];
    }else if ([strTitle isEqualToString:@"常见问题"]) {
        vc = [CommonProblemVC new];
    }else if ([strTitle isEqualToString:@"增值服务-车检检测业务"]) {
        vc = [ZTXInforQYViewController new];
    }else if ([strTitle isEqualToString:@"免验授权"]) {
        [self getCallVisaFreeApi];
    }else if ([strTitle isEqualToString:@"关于我们"]) {
        vc = [AboutOurVC new];
    }

    //
    if ([vc isKindOfClass:[AboutOurVC class]]) {
        [self pushVc:vc];
    }else{
        if ([CJControl isLogin]) {
            [self pushVc:vc];
        }else{
            [self showLoginWindowALert];
        }
    }

}

- (void)didSelectCompanyMembersAction{


    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/role/shipmentRoles",CJBaseUrl);
 
    WS(ws);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:GetType url:strUrl parameters:@{} status:ArpaDefault success:^(id  _Nonnull responseObject) {
        
        CompanyMembersVC *vc = [CompanyMembersVC new];
        NSError *error;
        NSArray<CompanyMembersModel *>  *arr = [CompanyMembersModel arrayOfModelsFromDictionaries:(NSArray *)responseObject error:&error];
        vc.listCompanyModel = arr;
        [ws pushVc:vc];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark ----------免验接口-------
- (void)getCallVisaFreeApi{
    
    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-tms-api/mybankMerchantprodMerch/merchPreapply",CJBaseUrl);

    NSDictionary *dicPra = @{@"sysType":@"app",
                             @"appType":@"ntoccshipper",
                             @"page":@"main",
                             @"branchCode":BranchCode
    };

    [[HDNetworking sharedHDNetworking] POST:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:responseObject]];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)getArrTitleAndContent{
    [self.arrTitlesList removeAllObjects];
    [self.arrImgsList removeAllObjects];
    if (![CJControl getUIWithNew]) {
        [self.arrTitlesList addObject:@"认证信息"];
        [self.arrImgsList addObject:@"zcj_icon_user"];
    }
    
    if ([CJControl getIsCompany]) {
        [self.arrTitlesList addObject:@"公司成员"];
        [self.arrImgsList addObject:@"zcj_icon_gongsichengyuan"];
    }

    [self.arrTitlesList addObject:@"保单列表"];
    [self.arrImgsList addObject:@"zcj_baoDan"];
    
    if (![CJControl getUIWithNew]) {
        [self.arrTitlesList addObject:@"电子合同"];
        [self.arrImgsList addObject:@"zcj_icon_hetong"];
    }
    
    [self.arrTitlesList addObject:@"货主合同"];
    [self.arrImgsList addObject:@"zcj_icon_huozhuhetong"];
    
    [self.arrTitlesList addObject:@"发票索取"];
    [self.arrImgsList addObject:@"zcj_icon_mine_fapiao"];
    
    [self.arrTitlesList addObject:@"承运分组"];
    [self.arrImgsList addObject:@"zcj_icon_fenzu"];
    
    [self.arrTitlesList addObject:@"法律咨询"];
    [self.arrImgsList addObject:@"zcj_faLu"];
    
    [self.arrTitlesList addObject:@"数据统计"];
    [self.arrImgsList addObject:@"zcj_icon_shuju"];
    
    [self.arrTitlesList addObject:@"常用信息"];
    [self.arrImgsList addObject:@"zcj_icon_share"];
    
    if (![CJControl getUIWithNew]) {
        [self.arrTitlesList addObject:@"我的评价"];
        [self.arrImgsList addObject:@"zcj_icon_commnet"];
        
        [self.arrTitlesList addObject:@"投诉记录"];
        [self.arrImgsList addObject:@"zcj_icon_tousu"];
    }
    
    [self.arrTitlesList addObject:@"投诉意见反馈"];
    [self.arrImgsList addObject:@"zcj_icon_yijian"];
    
    [self.arrTitlesList addObject:@"常见问题"];
    [self.arrImgsList addObject:@"zcj_icon_changjian"];
    
    [self.arrTitlesList addObject:@"增值服务-车检检测业务"];
    [self.arrImgsList addObject:@"zcj_icon_fenzu"];
    
//    2022-03-17  网商2.0 迭代去掉
//    if ([CJControl getShowAccountBalanceVisafree]) {
//        [self.arrTitlesList addObject:@"免验授权"];
//        [self.arrImgsList addObject:@"zcj_mianqian"];
//    }

    [self.arrTitlesList addObject:@"关于我们"];
    [self.arrImgsList addObject:@"zcj_icon_info"];

}

#pragma mark -- lazy ---

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, header.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - kTabBarHeight  -CJTableToTopHeight - header.height),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeader(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
    
            if (isheader) {
                [ws headerRereshing];
            } else {
                [ws.tableView.mj_footer endRefreshing];
                [ws.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        };
        _footerView = [[MineFooterView alloc] init];
        _footerView.height = LW(70);
        _tableView.tableFooterView= _footerView;
    }
    
    return _tableView;
}

- (NSMutableArray *)arrTitlesList{
    if (!_arrTitlesList) {
        _arrTitlesList = [[NSMutableArray alloc]init];
    }
    return _arrTitlesList;;
}

- (NSMutableArray *)arrImgsList{
    if (!_arrImgsList) {
        _arrImgsList = [[NSMutableArray alloc]init];
    }
    return _arrImgsList;;
}
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
 {
     CGRect extent = CGRectIntegral(image.extent);
     CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));

     // 1.创建bitmap;
     size_t width = CGRectGetWidth(extent) * scale;
     size_t height = CGRectGetHeight(extent) * scale;
     CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
     CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
     CIContext *context = [CIContext contextWithOptions:nil];
     CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
     CGContextScaleCTM(bitmapRef, scale, scale);
     CGContextDrawImage(bitmapRef, extent, bitmapImage);

     // 2.保存bitmap到图片
     CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
     CGContextRelease(bitmapRef);
     CGImageRelease(bitmapImage);
     return [UIImage imageWithCGImage:scaledImage];
 }
-(UIView *)bgView{
    if (_bgView == nil) {
        self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        self.bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
        [self.bgView addSubview:self.nameLabel];
        [self.bgView addSubview:self.erwImagView];
        self.changeVoidceSet = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeVoidceSet:)];
        [self.bgView addGestureRecognizer:self.changeVoidceSet];
    }
    return _bgView;
}
- (UIImageView *)erwImagView{
    if(_erwImagView == nil){
        self.erwImagView = [[UIImageView alloc] initWithFrame:CGRectMake(30, (SCREEN_HEIGHT - (SCREEN_WIDTH - 60))/2, SCREEN_WIDTH - 60, SCREEN_WIDTH - 60)];
        self.erwImagView.image = self.erWeiMaImag;
    }
    return _erwImagView;
}
- (UILabel *)nameLabel {
    if(_nameLabel == nil){
        self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, (SCREEN_HEIGHT - (SCREEN_WIDTH - 60))/2 - 20, SCREEN_WIDTH - 60, 20)];
        self.nameLabel.textAlignment = NSTextAlignmentCenter;
        self.nameLabel.textColor = [UIColor cjMainColorText];
        self.nameLabel.text = self.labName.text;
        self.nameLabel.backgroundColor = [UIColor whiteColor];
    }
    return _nameLabel;
}
- (void)changeVoidceSet:(UITapGestureRecognizer *)sender {
    CGPoint location = [sender locationInView:self.bgView];
//    DebugLog(@"--x:%f    y:%f",location.x,location.y);
    if (location.y <= (SCREEN_HEIGHT - (SCREEN_WIDTH - 60))/2 - 10 || location.y > (SCREEN_HEIGHT - (SCREEN_WIDTH - 60))/2 +  (SCREEN_WIDTH - 60)) {
        [self.bgView removeFromSuperview];
    }
}
@end

